package com.sk.bilibili.view.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.sk.bilibili.dto.GenericInfo;
import com.sk.bilibili.model.BaseModel;
import com.sk.bilibili.utils.GenericUtils;
import com.sk.bilibili.view.BaseView;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

import lombok.SneakyThrows;

public abstract class BaseFragment<T extends ViewBinding,M extends BaseModel> extends Fragment
        implements BaseView {

    protected T bind;
    protected M model;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        init(container);
        return bind.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        afterSetView();
        model.loadData();
    }

    protected abstract void afterSetView();

    @SneakyThrows
    private void init(ViewGroup container) {
        GenericInfo<T, M> info = GenericUtils.parse(getClass());
        // initBind
        Class<T> bindClass = info.getBindClass();
        Method inflate = bindClass.getDeclaredMethod("inflate", LayoutInflater.class,ViewGroup.class,boolean.class);
        bind= (T) inflate.invoke(null,getLayoutInflater(),container,false);
        // initModel
        Class<M> modelClass= info.getModelClass();
        model= modelClass.newInstance();
        model.setView(this);
    }

    protected void toast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void loadError() {

    }

}